package com.book.controller.admin;


import com.book.controller.BaseController;
import com.book.model.MsgVo;
import com.book.model.criteria.Criteria;
import com.book.model.criteria.Restrictions;
import com.book.model.entity.ArticleGroup;
import com.book.model.repository.ArticleGroupRepository;
import com.book.model.repository.UserRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/4/2.
 */
@Api( value = "文章分组管理", description = "文章分组的接口",tags="admin-article-group")
@RestController("admin_article_group_controller")
@RequestMapping("/api/admin/article/group")
@CrossOrigin
public class ArticleGroupController extends BaseController {
    @Autowired
    ArticleGroupRepository articleGroupRepository;
    @Autowired
    UserRepository userRepository;



    @ApiOperation(value="列表", notes="列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页行数,默认10条", required = false, dataType = "int", paramType = "query"),
    })
    @RequestMapping(value = "",method = RequestMethod.GET)
    @ResponseBody
    public MsgVo list(

            @RequestParam(value = "id",defaultValue = "0")Long id,
            @RequestParam(value = "page",defaultValue = "1")Integer page,
            @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize){

        MsgVo msgVo =new MsgVo();

        Criteria<ArticleGroup> criteria = new Criteria<>();
        if(id > 0){
            criteria.add(Restrictions.eq("id",id));
        }
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable =  new PageRequest(page-1, pageSize, sort);
        Page<ArticleGroup> articleGroups = articleGroupRepository.findAll(criteria,pageable);

        msgVo.getData().put("articleGroups",articleGroups);
        msgVo.setMsg("获取成功");
        return msgVo;
    }

    @ApiOperation(value="树结构列表", notes="树结构列表")
    @ApiImplicitParams({
    })
    @RequestMapping(value = "/tree",method = RequestMethod.GET)
    @ResponseBody
    public MsgVo tree(){
        MsgVo msgVo =new MsgVo();
        List<ArticleGroup> articleGroups = articleGroupRepository.findAll();
        msgVo.getData().put("articleGroupsTree",recursionGroup(articleGroups));
        msgVo.setMsg("获取成功");
        return msgVo;
    }

    private List recursionGroup(List<ArticleGroup> list){
        List treeList = new ArrayList();
        // 循环查出的list，找到根节点（最大的父节点）的子节点
        for(ArticleGroup group : list){
            // 我们这里最大的根节点ID是-1，所以首先找pid为-1的子，然后调用我们的递归算法
            if(group.getParentID() == 0){
                treeList.add(addChildMenu(group,list));
            }
        }
        return treeList;
    }

    private ArticleGroup addChildMenu(ArticleGroup parentMap, List<ArticleGroup> list) {
        List<ArticleGroup> childList = new ArrayList<>();
        // 为每一个父节点增加子树（List形式，没有则为空的list）
        parentMap.setChildren(childList);
        for (ArticleGroup childMap : list) {
            //如果子节点的pid等于父节点的ID，则说明是父子关系
            if (childMap.getParentID() == parentMap.getId()) {
                // 是父子关系，则将其放入子list字面
                childList.add(childMap);
                // 继续调用递归算法，将当前作为父节点，继续找他的子节点，反复执行。
                addChildMenu(childMap, list);
            }
        }
        // 当遍历完成，返回调用的父节点的所有子节点
        return parentMap;
    }

    @ApiOperation(value="创建/修改", notes="创建/修改")
    @ApiImplicitParams({
    })
    @RequestMapping(value = "",method = RequestMethod.POST)
    @ResponseBody
    public MsgVo add(@RequestParam(value = "id",defaultValue = "0")Long id,
                     @RequestParam("name")String name,
                     @RequestParam(value = "parent_id",defaultValue = "0")Long parentID

    ){
        MsgVo msgVo = new MsgVo();
        ArticleGroup articleGroup = null;
        if(id > 0){
            articleGroup = articleGroupRepository.findById(id).orElse(null);
            if(articleGroup == null){
                msgVo.setCode(40002);
                msgVo.setMsg("分组不存在");
                return msgVo;
            }
        }else{
            articleGroup = new ArticleGroup();
        }
        articleGroup.setName(name);
        articleGroup.setParentID(parentID);
        articleGroupRepository.save(articleGroup);
        return msgVo;
    }

    @ApiOperation(value="删除", notes="删除")
    @ApiImplicitParams({
    })
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public MsgVo delete(@PathVariable("id")Long id){
        MsgVo msgVo = new MsgVo();

        ArticleGroup articleGroup = articleGroupRepository.findById(id).orElse(null);
        if(articleGroup == null){
            msgVo.setCode(40001);
            msgVo.setMsg("分组不存在");
            return msgVo;
        }
        //TODO 判断是否有文章
        articleGroupRepository.delete(articleGroup);
        return msgVo;
    }

}
